package com.sinosoft.cpyy.util.fnnc;


import com.sinosoft.util.CollectionUtil;

import com.sinosoft.util.excel.ExcelMapModel;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddressList;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Component;
import java.io.*;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import static com.sinosoft.util.CollectionUtil.splitList;


/**
 * describe <br>
 * datetime 2017-12-25 10:55<br>
 * @author 张清森
 */
@Component
@Slf4j
public final class FnncUtils implements Serializable{


    private static final long serialVersionUID = 8068280866747516068L;

    /**
     * 校验日期
     */
    public static boolean judgeDate(String dates) {

        String eL= "^((\\d{2}(([02468][048])|([13579][26]))[\\/\\s]?((((0?[13578])|(1[02]))[\\/\\s]?((0?[1-9])|([1-2][0-9])|(3[01])))|(((0?[469])|(11))[\\/\\s]?((0?[1-9])|([1-2][0-9])|(30)))|(0?2[\\/\\s]?((0?[1-9])|([1-2][0-9])))))|(\\d{2}(([02468][1235679])|([13579][01345789]))[\\/\\s]?((((0?[13578])|(1[02]))[\\/\\s]?((0?[1-9])|([1-2][0-9])|(3[01])))|(((0?[469])|(11))[\\/\\s]?((0?[1-9])|([1-2][0-9])|(30)))|(0?2[\\/\\s]?((0?[1-9])|(1[0-9])|(2[0-8]))))))";
        Pattern p = Pattern.compile(eL);
        Matcher m = p.matcher(dates);
        boolean result = m.matches();
        return result;
    }
    public static String downloadExcel2003(ExcelMapModel fileMod, String path) throws Exception {
        return FnncUtils.downloadExcelFile2003Util(fileMod, path);
    }

    /**
     * 表格生成并下载
     */
    private static String downloadExcelFile2003Util(ExcelMapModel fileMod, String path) throws IOException{
        String mes = "";
        if (null != fileMod) {
            List<ExcelMapModel> modeList = checkOrSplitList(fileMod);
            mes = downBatchExcelFile2003Util(modeList, path);
        }

        return mes;
    }
    private static List<ExcelMapModel> checkOrSplitList(ExcelMapModel excelMapModel) {
        List<ExcelMapModel> modeList = new ArrayList();
        if (excelMapModel.getMapList().size() > 60000) {
            List<List<LinkedHashMap<String, Object>>> resultList = splitList(excelMapModel.getMapList(), 60000);

            for(int i = 0; i < resultList.size(); ++i) {
                ExcelMapModel newExcelMapModel = new ExcelMapModel();
                BeanUtils.copyProperties(excelMapModel, newExcelMapModel, new String[]{"mapList"});
                newExcelMapModel.setMapList((List)resultList.get(i));
                newExcelMapModel.setSheetName(excelMapModel.getSheetName() + "_" + i);
                modeList.add(newExcelMapModel);
            }
        } else {
            modeList.add(excelMapModel);
        }

        return modeList;
    }
    public static String downBatchExcelFile2003Util(List<ExcelMapModel> fileMods, String path) throws IOException {
        String filePath = path + File.separatorChar;
        String fileTempName = filePath + System.currentTimeMillis() + ".xls";

        try {
            HSSFWorkbook workbook = new HSSFWorkbook();
            Throwable var5 = null;

            try {
                File file = new File(filePath);
                if (!file.exists() || !file.isDirectory()) {
                    boolean mkdirs = file.mkdirs();
                    if (!mkdirs) {
                        throw new NullPointerException("文件夹不存在或创建失败！");
                    }
                }

                if (!CollectionUtil.collectionIsNull(fileMods)) {
                    for(int k = 0; k < fileMods.size(); ++k) {
                        ExcelMapModel excelMapModel = (ExcelMapModel)fileMods.get(k);
                        List<ExcelMapModel> modeList = checkOrSplitList(excelMapModel);
                        Iterator var10 = modeList.iterator();

                        while(var10.hasNext()) {
                            ExcelMapModel fileMod = (ExcelMapModel)var10.next();
                            createExcel2003(workbook, k, fileMod);
                        }
                    }

                    FileOutputStream os = new FileOutputStream(fileTempName);
                    workbook.write(os);
                    os.flush();
                    os.close();
                }
            } catch (Throwable var21) {
                var5 = var21;
                throw var21;
            } finally {
                if (workbook != null) {
                    if (var5 != null) {
                        try {
                            workbook.close();
                        } catch (Throwable var20) {
                            var5.addSuppressed(var20);
                        }
                    } else {
                        workbook.close();
                    }
                }
            }
            return fileTempName;
        } catch (FileNotFoundException var23) {
            throw new FileNotFoundException(var23.getMessage());
        } catch (IOException var24) {
            throw new IOException(var24.getMessage());
        }
    }
    /**
     * 创建表格
     */
    private static void createExcel2003(HSSFWorkbook workbook, int index, ExcelMapModel fileMod) {
        String[][] heades = fileMod.getHeaders();
        if (null ==fileMod.getMapList()) {
            throw new NullPointerException("传入的参数ExcelMapModel对象中的集合属性为空，参数传入错误，不能生成Excel！");
        } else {
            String sheetName = null == fileMod.getSheetName() ? "sheet" + index : fileMod.getSheetName();
            HSSFSheet sheet = workbook.createSheet(sheetName);
            HSSFCellStyle style = workbook.createCellStyle();
            createHeaderCellStyle(style);
            HSSFCellStyle textStytle = workbook.createCellStyle();
            HSSFDataFormat format = workbook.createDataFormat();
            textStytle.setDataFormat(format.getFormat("@"));
            createCellStyle(textStytle);
            HSSFRow row = sheet.createRow(0);
            int colSize = fileMod.getHeaders().length;
            //设置表头
            for(int i = 0; i < colSize; ++i) {
                HSSFCell cell = row.createCell(i);
                String colName = heades[i][1];
                createCell(style, cell, colName);
                sheet.setColumnWidth(i, (null != fileMod.getWidths() && fileMod.getWidths().length > i ? fileMod.getWidths()[i] : 30) * 256);
            }
            //设置主体
            createRow(fileMod, sheet, textStytle,style);
        }
    }
    /**
     * 创建行
     */
    private static void createRow(ExcelMapModel fileMod, HSSFSheet sheet, HSSFCellStyle textStytle,HSSFCellStyle Style) {
        int totalSize = fileMod.getMapList().size();
        String[][] heades = fileMod.getHeaders();
        int colSize = heades.length;
        String[] textlist={"专票","普票"};
        int lastRow = totalSize;
        if (lastRow<1){
            lastRow=1;
        }

        sheet = setHSSFValidation(sheet, textlist, 1, lastRow, 6, 6);
        String[] text={"服务费","代收社保","代收公积金","代收社保、公积金","代收工资"};
        sheet = setHSSFValidation(sheet, text, 1, lastRow, 7, 7);
        Object flag=null;
        //创建行
        for(int j = 0; j < totalSize; ++j) {
            LinkedHashMap<String, Object> obj = (LinkedHashMap)fileMod.getMapList().get(j);
            HSSFRow row = sheet.createRow(j + 1);

            //创建格
            for(int n = 0; n < colSize; ++n) {
                String value = null != obj.get(heades[n][0]) ? obj.get(heades[n][0]).toString() : "";
                HSSFCell cell = row.createCell(n);
                if (!cell.getCellTypeEnum().equals(CellType.STRING)) {
                    cell.setCellType(CellType.STRING);
                }
                if (j==0||flag!=obj.get(heades[1][0])){

                    cell.setCellStyle(textStytle);
                }

                cell.setCellValue(value);
                cell.setCellType(CellType.STRING);
            }
            flag=obj.get(heades[1][0]);
        }

    }
    /**
     * 创建表格单元格
     */
    private static void createCell(HSSFCellStyle style, HSSFCell cell, String colName) {
        if (!cell.getCellTypeEnum().equals(CellType.STRING)) {
            cell.setCellType(CellType.STRING);
        }

        cell.setCellStyle(style);
        HSSFRichTextString text = new HSSFRichTextString(colName);
        cell.setCellValue(text);
        cell.setCellType(CellType.STRING);
    }
    /**
     * 创建表头表格样式
     */
    private static void createHeaderCellStyle(HSSFCellStyle style) {
        style.setFillForegroundColor(IndexedColors.SKY_BLUE.getIndex());
        style.setFillPattern(FillPatternType.SOLID_FOREGROUND);
        style.setBorderBottom(BorderStyle.THIN);
        style.setBorderLeft(BorderStyle.THIN);
        style.setBorderRight(BorderStyle.THIN);
        style.setBorderTop(BorderStyle.THIN);
        style.setAlignment(HorizontalAlignment.CENTER);
    }
    /**
     * 创建隔行样式
     */
    private static void createCellStyle(HSSFCellStyle style) {
        style.setFillForegroundColor(IndexedColors.YELLOW.getIndex());
        style.setFillPattern(FillPatternType.SOLID_FOREGROUND);
        style.setBorderBottom(BorderStyle.THIN);
        style.setBorderLeft(BorderStyle.THIN);
        style.setBorderRight(BorderStyle.THIN);
        style.setBorderTop(BorderStyle.THIN);
        style.setAlignment(HorizontalAlignment.LEFT);
        style.setWrapText(true);
    }
    /**
     * 设置某些列的值只能输入预制的数据,显示下拉框.
     *
     * @param sheet
     *            要设置的sheet.
     * @param textlist
     *            下拉框显示的内容
     * @param firstRow
     *            开始行
     * @param endRow
     *            结束行
     * @param firstCol
     *            开始列
     * @param endCol
     *            结束列
     * @return 设置好的sheet.
     */
    public static HSSFSheet setHSSFValidation(HSSFSheet sheet,
                                              String[] textlist, int firstRow, int endRow, int firstCol,
                                              int endCol) {
        // 加载下拉列表内容
        DVConstraint constraint = DVConstraint
                .createExplicitListConstraint(textlist);
        // 设置数据有效性加载在哪个单元格上,四个参数分别是：起始行、终止行、起始列、终止列
        CellRangeAddressList regions = new CellRangeAddressList(firstRow,
                endRow, firstCol, endCol);
        // 数据有效性对象
        HSSFDataValidation data_validation_list = new HSSFDataValidation(
                regions, constraint);
        sheet.addValidationData(data_validation_list);
        return sheet;
    }

    public static boolean judgeCard(String certNo) {
        if (certNo.length()==15||certNo.length()==18){
            return true;
        }else {
            return false;
        }
    }
}

